package com.xwsz.demo.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class WordUtils {

	@SuppressWarnings("unchecked")
    public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
        try {
            //创建配置实例
            Configuration configuration = new Configuration();

            //设置编码
            configuration.setDefaultEncoding("UTF-8");

            //ftl模板文件
            configuration.setClassForTemplateLoading(WordUtils.class,"/");

            //获取模板
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile = new File(filePath+File.separator+fileName);

            //如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));


            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	 public static void main(String[] args) {
         /** 用于组装word页面需要的数据 */
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Map<String,String>> datas = new ArrayList<>();
        for(int i=0;i<10;i++){
        	Map<String,String> updateInfo = new HashMap<>();
        	updateInfo.put("updateBy","sys");
        	updateInfo.put("updateContent","第"+(i+1)+"次修改");
        	updateInfo.put("updateDate","2022-01-06 15:51:12");
        	updateInfo.put("updateVersion",(i+1)+"");
            datas.add(updateInfo);
        }
        System.err.println(JSON.toJSONString(datas));
        dataMap.put("updateList",datas);
        dataMap.put("title","测试文档标题");
        String filePath = "D:/doc_f/";
        //文件唯一名称
        String fileOnlyName = "生成Word文档.doc";
        /** 生成word  数据包装，模板名，文件生成路径，生成的文件名*/
        createWord(dataMap, "template/wordTest.ftl", filePath, fileOnlyName);
    }
}
